package controllers

import (
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/request/BaseReq"
	"gdshop-back-end-go/common/request/CommonReq"
	"gdshop-back-end-go/common/response"
	"gdshop-back-end-go/service-other/AreaService"
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
)

type CommonController struct {
	*BaseController
}

func NewCommonController(inputReq *BaseReq.I) *CommonController {
	return &CommonController{
		&BaseController{Req: inputReq},
	}
}

func (c *CommonController) AreaTree(r *ghttp.Request) *response.JsonResponse {
	if err := r.Parse(&c.Req.PageInfo); err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}
	return AreaService.Tree(r, c.Req)
}

func (c *CommonController) AreaList(r *ghttp.Request) *response.JsonResponse {
	if err := r.Parse(&c.Req.PageInfo); err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}
	return AreaService.List(r, c.Req)
}

func (c *CommonController) AreaLevelList(r *ghttp.Request) *response.JsonResponse {
	if err := r.Parse(&c.Req.PageInfo); err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}
	return AreaService.LevelList(r, c.Req)
}

func (c *CommonController) AreaAllLevelList(r *ghttp.Request) *response.JsonResponse {
	if err := r.Parse(&c.Req.PageInfo); err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}
	return AreaService.AreaAllLevelList(r, c.Req)
}

func (c *CommonController) DiyForm(r *ghttp.Request) *response.JsonResponse {
	formKey := r.GetString("form_key", "")
	if formKey == "" {
		return response.FailByRequestMessage(r, "form_key不能为空")
	}
	ctx := r.GetCtx()
	value, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "diy_form").Where("status = 1 AND form_key = ?", formKey).Value("form_config")
	if err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}
	if value.IsNil() {
		return response.FailByRequestMessage(r, "表单不存在")
	}
	if value.String() == "" {
		return response.FailByRequestMessage(r, "表单内容为空")
	}
	json, err := gjson.DecodeToJson(value.String())
	if err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}
	return response.SuccessByRequestMessageData(r, "成功", json)
}

func (c *CommonController) RemoteData(r *ghttp.Request) *response.JsonResponse {
	var params *CommonReq.RemoteData
	if err := r.Parse(&params); err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}
	ctx := r.GetCtx()
	if params.Type == "category" {
		where := gconv.Map(params.Where)
		all, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "category").Where(where).
			OrderDesc("sort").
			Fields("id, cat_name AS name,parent_id").All()
		if err != nil {
			return response.FailByRequestMessage(r, err.Error())
		}
		return response.SuccessByRequestMessageData(r, "成功", all)
	}

	return response.FailByRequestMessage(r, "不支持的类型")
}
